package com.zhiwei.msf.infra.oauth.config;

import org.springframework.security.access.AccessDecisionManager;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import java.util.Collection;


/**
 * 权限决策管理器
 */
@Component
public class AuthorityAccessDecisionManager implements AccessDecisionManager {

    /**
     * @param authentication   已认证数据
     * @param object           授权对象，例如网络路径
     * @param configAttributes 授权对象配置规则集合(SecurityMetadataSource 定义)
     * @throws AccessDeniedException
     * @throws InsufficientAuthenticationException
     */
    @Override
    public void decide(Authentication authentication, Object object, Collection<ConfigAttribute> configAttributes) throws AccessDeniedException, InsufficientAuthenticationException {
        if (CollectionUtils.isEmpty(configAttributes)) {
            return;
        }
        for (ConfigAttribute configAttribute : configAttributes) {
            String needPermission = configAttribute.getAttribute();
            //白名单校验
            if(needPermission.equalsIgnoreCase(SecurityConstants.WHITE_LIST_ROLE)){
                return;
            }

            //认证不鉴权
            if(needPermission.equalsIgnoreCase(SecurityConstants.Authenticated)){
                return;
            }
            //认证、鉴权
            for (GrantedAuthority grantedAuthority : authentication.getAuthorities()) {
                if (needPermission.trim().equalsIgnoreCase(grantedAuthority.getAuthority())) {
                    return;
                }
            }
        }
        throw new AccessDeniedException("no permission");
    }

    @Override
    public boolean supports(ConfigAttribute configAttribute) {
        return true;
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return true;
    }
}